Skip to content

Start new tasks as soon as a running task finishes - #622

Merged
chrisguidry merged 1 commit into
mainfrom
wake-worker-on-task-completion
Nov 20, 2026
Merged

chrisguidry merged 1 commit into
mainfrom
wake-worker-on-task-completion

Conversation

@gaker

@gaker gaker commented Nov 20, 2026 •

Copy link
Copy Markdown
Collaborator

The problem. When every slot was busy, the worker slept for minimum_check_interval before it looked for finished tasks. That capped a worker at concurrency / minimum_check_interval tasks per second, however fast the tasks ran: 4 tasks/s per slot for Worker() (250 ms) and 10 for docket worker (100 ms).

The fix. The worker waits on its active tasks with asyncio.wait(..., return_when=FIRST_COMPLETED), using minimum_check_interval as the timeout. A slot that frees up takes new work at once. docket-rs already waits this way with JoinSet::join_next().

One Worker() process drained pre-enqueued no-op tasks from Redis 8.10 on the same machine, without hiredis. Each side ran three times with the same task count:

concurrency tasks main this branch
1 200 4 tasks/s 1,623–1,676 tasks/s
10 1,000 40 tasks/s 5,306–5,490 tasks/s
50 2,000 201 tasks/s 5,822–6,311 tasks/s

Main's numbers equal concurrency × 4 in every run, which is the cap the sleep sets. The rate is the task count divided by the time from the worker starting to the last task finishing. Over a network, each task's two Redis round trips cost more, so the branch's numbers will be lower; main's cap stays the same.

test_waiter_woken_before_its_safeguard_exists_cancels_the_safeguard polled for the woken waiter's queued state. The worker now claims and finishes the woken task before that poll runs, so the test checks that the state has left scheduled.

Rollout caveats

  • watch: Redis command rate from workers. A busy worker now reads the stream each time a task finishes, where it used to read once per interval, so XREADGROUP calls can rise with task completions
Benchmark script

Run it with a Redis on port 6390, for example python bench.py --n 1000 --concurrency 10.

"""Drain N pre-enqueued no-op tasks with one worker; report tasks/s.

The rate is N divided by the time from the worker starting to the last task
finishing, so run_until_finished's final empty polls are not counted.
"""

import argparse
import asyncio
import logging
import time
import uuid

from docket import Docket, Worker

finished_at: list[float] = []


async def noop() -> None:
    finished_at.append(time.perf_counter())


async def main() -> None:
    p = argparse.ArgumentParser()
    p.add_argument("--n", type=int, required=True)
    p.add_argument("--concurrency", type=int, required=True)
    p.add_argument("--url", default="redis://localhost:6390/0")
    args = p.parse_args()

    logging.disable(logging.CRITICAL)
    async with Docket(name=f"bench-{uuid.uuid4().hex[:8]}", url=args.url) as docket:
        docket.register(noop)
        for start in range(0, args.n, 1000):
            await docket.add_many(
                docket.call(noop)() for _ in range(min(1000, args.n - start))
            )
        async with Worker(docket, concurrency=args.concurrency) as worker:
            t0 = time.perf_counter()
            await worker.run_until_finished()
        await docket.clear()

    assert len(finished_at) == args.n, (len(finished_at), args.n)
    elapsed = max(finished_at) - t0
    print(f"c={args.concurrency} n={args.n} {args.n / elapsed:,.0f} tasks/s ({elapsed:.2f}s)")


asyncio.run(main())
Session context

This came out of benchmarking for throughput gains that need no API change. The same benchmark found that redis-py 7 and later cap the connection pool at 100 and raise MaxConnectionsError when it is full. A worker with concurrency near 100 then stops polling, and the messages it read stay pending until the redelivery timeout. That fix is in a separate branch. hiredis added about 40% on top of this change in the same benchmark.

🤖 Generated with Claude Code

When every slot was busy, the worker slept for minimum_check_interval
before it looked for finished tasks.  Throughput was therefore capped at
concurrency / minimum_check_interval: 4 tasks/s per slot for Worker()
(250 ms) and 10 for `docket worker` (100 ms), however fast tasks ran.
The worker now waits on its active tasks with FIRST_COMPLETED, using
the same interval as a timeout.  docket-rs already waits this way with
JoinSet::join_next().

test_waiter_woken_before_its_safeguard_exists_cancels_the_safeguard
polled for the woken waiter's "queued" state.  The worker now claims
and finishes the woken task before the poll runs, so the test checks
that the state has left "scheduled".

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
@chatgpt-codex-connector

chatgpt-codex-connector Bot commented Nov 20, 2026 •

Copy link
Copy Markdown
Codex Review Summary: ✅ Completed

This comment shows the latest Codex review activity on this pull request.

Review Status Commit Review trigger
📝 Code Review ✅ Completed 2026-11-20T20:44:41.890982Z 60b1c52 PR opened
ℹ️ About Codex in GitHub

Your team has set up Codex to review pull requests in this repo. Reviews are triggered when you

  • Open a pull request for review
  • Mark a draft as ready
  • Comment "@codex review" or "@codex security review".

Codex reacts with 👀 while any review is running, comments if it has suggestions, and reacts with 👍 once all reviews finish with no findings.

@read-the-docs-community

Copy link
Copy Markdown

Documentation build overview

📚 docket | 🛠️ Build #36053648 | 📁 Comparing 60b1c52 against latest (a4e1c22)

  🔍 Preview build  

1 file changed
± api-reference/index.html

@chrisguidry
chrisguidry enabled auto-merge (squash) November 20, 2026 20:48
@chrisguidry
chrisguidry merged commit 0a7bc3e into main Nov 20, 2026
105 of 107 checks passed
@chrisguidry
chrisguidry deleted the wake-worker-on-task-completion branch November 20, 2026 20:53
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants